// 用户认证状态管理
export interface User {
  id: string;
  email: string;
  name: string;
  role: string;
}

export interface AuthState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
}

// 从 localStorage 获取认证信息
export function getAuthFromStorage(): AuthState {
  if (typeof window === "undefined") {
    return { user: null, token: null, isAuthenticated: false };
  }

  const token = localStorage.getItem("token");
  const userStr = localStorage.getItem("user");

  if (!token || !userStr) {
    return { user: null, token: null, isAuthenticated: false };
  }

  try {
    const user = JSON.parse(userStr) as User;
    return { user, token, isAuthenticated: true };
  } catch {
    return { user: null, token: null, isAuthenticated: false };
  }
}

// 保存认证信息到 localStorage
export function saveAuthToStorage(user: User, token: string): void {
  if (typeof window === "undefined") return;

  localStorage.setItem("token", token);
  localStorage.setItem("user", JSON.stringify(user));
}

// 清除认证信息
export function clearAuthFromStorage(): void {
  if (typeof window === "undefined") return;

  localStorage.removeItem("token");
  localStorage.removeItem("user");
}

// 获取认证请求头
export function getAuthHeaders(): Record<string, string> {
  const { token } = getAuthFromStorage();
  return token ? { Authorization: `Bearer ${token}` } : {};
}
